<template>
  <div class="terminal-export">
    <el-row>
      <el-col v-if="type !== 'Terminal'" :span="6">
        <div v-if="!type" class="p-2 ml-4">
          <el-button size="small" type="primary" @click="selectAll">{{ $t('flyparam.select_all') }}</el-button>
          <el-button size="small" type="danger" @click="clear">{{ $t('flyparam.clear_choosed') }}</el-button>
        </div>
        <el-tree
          ref="tree"
          :show-checkbox="!type"
          :data="treeData"
          :expand-on-click-node="false"
          default-expand-all
          check-strictly
          node-key="id"
          @node-click="handleNodeClick"
          @check="handleTreeCheckChange"
        >
        <template v-slot="{node,data}">
          <div class="w-full">
            <div class="flex justify-between items-center w-full pr-3">
              <span v-ellipsis class="flex items-center inline-block" style="width: 150px;">
                <svg-icon :icon-class="_treeIconClass(data)" class-name="mr-2" />
                {{ data.name }}
              </span>
            </div>
          </div>
        </template>
        </el-tree>
      </el-col>
      <el-col :span="type !== 'Terminal' ? 18 : 24" class="right-col">
        <div v-if="type === 'Terminal'">
          <el-row class="px-5 py-3">
            <el-col :span="24" class="mb-2">
              <span style="line-height: 30px">{{ $t('flyparam.export_col_choose_title') }}:</span>
            </el-col>
            <el-col :span="24">
              <div class="text-left">
                <el-checkbox-group v-model="extraColumns">
                  <el-checkbox label="Version"><span v-ellipsis>{{ $t('flyparam.param_file_version')
                  }}</span></el-checkbox>
                  <el-checkbox label="Status"><span v-ellipsis>{{ $t('flyparam.param_file_status') }}</span></el-checkbox>
                  <el-checkbox label="Update Time"><span v-ellipsis>{{ this.$t('cmp.page_updateTime')
                  }}</span></el-checkbox>
                  <el-checkbox label="Release Time"><span v-ellipsis>{{ $t('flyparam.param_file_publish_time')
                  }}</span></el-checkbox>
                </el-checkbox-group>
              </div>
            </el-col>
          </el-row>

          <hr class="my-2">
        </div>

        <div v-if="tableName != ''">
          <div v-if="hasTerminalPermission">
            <div v-if="type === 'Terminal'">
              <div class="py-2">
                <el-input
                  v-model.trim="rowUniqueKeyLike"
                  size="small"
                  style="width:260px;padding:0px 20px"
                  placeholder="SN"
                  @keyup.native.enter="() => fetchTableData(activeTreeNode)"
                />
                <el-button
                  type="primary"
                  class="align-middle p-1.5"
                  size="small"
                  @click="handleSearch"
                >
                  <svg-icon icon-class="search" class-name="text-lg" />
                </el-button>
              </div>
              <el-table v-loading="loading" :data="tableData">
                <el-table-column
                  v-for="(col, index) in columns"
                  :key="col.key"
                  align="center"
                  show-overflow-tooltip
                  :width="columns.length > 7 ? '150' : ''"
                  :fixed="index === 0"
                  :label="col.label"
                  :prop="col.key"
                />
                <el-table-column v-if="tableData.length > 0" width="120px" align="center">
                  <template v-slot:header="scope">
                    <el-button v-if="showLoadMore" size="small" @click="loadMore">{{ $t('flyparam.load_more')
                    }}</el-button>
                  </template>
                </el-table-column>
              </el-table>
              <el-pagination :total="total" :current-page="pageNo" @current-change="handlePaginationChange" />
            </div>
            <el-tabs v-else v-model="activeTab" type="card">
              <el-tab-pane v-if="!type" :label="$t('flyparam.structure_pane')" name="preview">
                <configuration-preview :layout="this.layout" />
              </el-tab-pane>
              <el-tab-pane :label="$t('flyparam.data_pane')" name="table">
                <div class="py-2">
                  <!-- <span style="font-size:18px;padding-left: 20px;">{{ tableName }}</span> -->
                  <el-input
                    v-model.trim="rowUniqueKeyLike"
                    size="small"
                    style="width:260px;padding:0px 20px"
                    placeholder="SN"
                    @keyup.native.enter="() => fetchTableData(activeTreeNode)"
                  />
                  <el-button
                    type="primary"
                    class="align-middle p-1.5"
                    size="small"
                    @click="handleSearch"
                  >
                    <svg-icon icon-class="search" class-name="text-lg" />
                  </el-button>
                </div>
                <el-table v-loading="loading" :data="tableData">
                  <el-table-column
                    v-for="(col, index) in columns"
                    :key="col.key"
                    show-overflow-tooltip
                    :width="columns.length > 7 ? '150' : ''"
                    :fixed="index === 0"
                    :label="col.label"
                    :prop="col.key"
                  />
                  <el-table-column v-if="tableData.length > 0" width="120px">
                    <template v-slot:header="scope">
                      <el-button v-if="showLoadMore" size="small" @click="loadMore">{{ $t('flyparam.load_more')
                      }}</el-button>
                    </template>
                  </el-table-column>
                </el-table>
                <el-pagination :total="total" :current-page="pageNo" @current-change="handlePaginationChange" />
              </el-tab-pane>
            </el-tabs>
          </div>
          <div v-else-if="layout.length > 0">
            <configuration-preview :layout="this.layout" />
          </div>
          <div v-else>
            <!-- TODO: -->
            <el-empty slot="empty" :image-size="100" :description="$t('common.no_data')" />
          </div>
        </div>
        <el-empty v-else :image-size="200" :description="$t('flyparam.table_not_choosed_tip')" />
      </el-col>
    </el-row>
  </div>
</template>

<script>
import {
  getReferenceEntryRecord,
  getReferenceTerminalTableRecord,
  downloadExcelImportTemplate,
  downloadTerminalExcelImportTemplate,
  exportParameterTemplateStructureAndData,
  exportParameterTemplateStructure,
  exportParameterTemplateData,
  exportTerminalTableData,
  exportRefTableData,
  getTemplateTableLayoutList
} from '@/api/parameter'
import { isObjectBoolean } from '@/utils'
import common from '@/utils/common'
import { formatDate } from '@/utils/formatDate'
import { mapLayoutData, treeIconClass } from '../helper'
import ConfigurationPreview from './configuration-preview'

function createLink(url) {
  const a = document.createElement('a')
  a.setAttribute('href', url)
  a.click()
}

export default {
  components: {
    ConfigurationPreview
  },
  props: {
    treeData: {
      type: Array
    },
    tableType: {
      type: Number
    },
    tableId: {
      type: String
    },
    checkedKeys: {
      type: Array
    },
    type: {
      type: String
    },
    templateId: String
  },
  data() {
    return {
      tableName: '',
      data: [],
      tableData: [],
      pageNo: 1,
      pageSize: 10,
      paramNum: 5,
      total: 0,
      columns: [],
      columnsCount: 0,
      loading: false,
      rowUniqueKeyLike: '',
      nodeDataId: '',
      hasTerminalPermission: false,
      layout: [],
      activeTab: 'preview',
      activeTreeNode: {},
      showLoadMore: true,
      extraColumns: []
    }
  },
  mounted() {
    let data = null
    if (this.type === 'Terminal') {
      data = this.treeData[0]
    } else {
      data = this.$refs.tree.getNode(this.tableId).data
    }
    this.fetchTableData(data)
    this.activeTreeNode = data
  },
  methods: {
    _treeIconClass(data) {
      return treeIconClass(data)
    },
    handleNodeClick(data) {
      // if (this.activeTreeNode === data) {
      //   return
      // }
      if (this.type === 'Terminal' && this.tableId !== data.id) {
        return
      }
      this.activeTreeNode = data

      this.fetchLayoutData(data)
      this.columnsCount = 0
      // this.columns = []
      this.fetchTableData(data)
    },
    fetchLayoutData(data) {
      getTemplateTableLayoutList(this.templateId, data.id).then((data) => {
        this.layout = data.map(item => {
          return mapLayoutData.call(this, item)
        })
      })
    },
    handleSearch() {
      this.columnsCount = 0
      this.fetchTableData(this.activeTreeNode)
    },
    fetchTableData(data, paramNum = 5) {
      if (data) {
        this.nodeDataId = data.id
        this.tableName = data.name
      }

      this.activeTab = 'table'

      this.loading = true
      let request = null
      if (data && data.tableType !== 1) {
        request = getReferenceEntryRecord
        this.hasTerminalPermission = true
        if (!this.type) {
          this.hasTerminalPermission = false
        }
      }
      if (request) {
        request(this.templateId, this.nodeDataId, {
          pageNo: this.pageNo,
          pageSize: this.pageSize,
          paramNum,
          rowUniqueKeyLike: this.rowUniqueKeyLike
        })
          .then((data) => {
            this.total = data.total

            if (this.columnsCount >= data.columns.length - 1) {
              this.showLoadMore = false
            } else {
              this.showLoadMore = true
            }
            this.columnsCount = data.columns.length - 1
          this.columns = data.columns.filter((col) => col.key !== '$id')

            this.tableData = data.items.map((item) => {
              const keys = Object.keys(item)
              const ret = {}
              for (let i = 0; i < keys.length; i++) {
                const key = keys[i]
                ret[key] = isObjectBoolean(item[key][0])
                  ? item[key][0] + ''
                  : item[key][0]
              }
              return ret
            })
          })
          .catch((err) => {
            if (err.message) this.$message.error(err.message)
          })
          .finally(() => {
            this.loading = false
          })
      } else {
        this.loading = false
      }
    },
    handlePaginationChange(page) {
      this.pageNo = page
      this.columns = []
      this.fetchTableData(this.activeTreeNode)
    },
    handleTreeCheckChange(currentNode, checkAllNode) {
      this.$emit('check', checkAllNode.checkedKeys)
    },
    clear() {
      if (this.$refs.tree) {
        this.$refs.tree.setCheckedKeys([])
      }

      this.$emit('check', [])
    },
    selectAll() {
      if (this.treeData.length > 0) {
        const keys = [this.treeData[0].id]
        if (this.treeData[0].children) {
          keys.push(...this.treeData[0].children.map((data) => data.id))
        }
        this.$refs.tree.setCheckedKeys(keys, true)
        this.$emit('check', keys)
      }
    },
    loadMore() {
      this.paramNum += 10
      this.fetchTableData(this.activeTreeNode, this.paramNum)
    },
    download(data) {
      let request
      if (this.tableType === 1) {
        request = downloadTerminalExcelImportTemplate
      } else {
        request = downloadExcelImportTemplate
      }
      const loading = this.$loading({
        lock: true,
        text: this.$t('flyparam.please_wait'),
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      request(this.templateId, data.id)
        .then((res) => {
          loading.close()
          // createLink(res.url)
          common.downloadFile(
            res,
            this.$store.state.parameter.appName +
            '-' +
            this.tableName +
            '-import-template',
            '.xlsx'
          )
        })
        .catch(() => {
          loading.close()
        })
    },
    confirm(mode) {
      // this.$emit('requesting')
      if (this.type === 'Terminal') {
        exportTerminalTableData(
          this.templateId,
          this.tableId,
          this.rowUniqueKeyLike,
          this.extraColumns
        ).then((res) => {
          // this.$emit('requested')
          if (res.size > 0) {
            common.downloadFile(
              res,
              'Data-' +
              this.$store.state.parameter.appName +
              '-' +
              this.tableName +
              '-export-' +
              formatDate(new Date().getTime() / 1000, 'YYYYMMDD-hhmmss'),
              '.xlsx'
            )
          } else {
            this.$message.success(this.$t('common.export_processing'))
            this.$store.dispatch('app/fetchTaskData')
          }
        }).catch((err) => {
          this.$confirmError(err)
          this.$emit('error')
        })
      } else if (this.type === 'Reference') {
        exportRefTableData(
          this.templateId,
          this.tableId,
          this.rowUniqueKeyLike
        ).then((res) => {
          this.$emit('requested')
          if (res.size > 0) {
            common.downloadFile(
              res,
              'Data-' +
              this.$store.state.parameter.appName +
              '-' +
              this.tableName +
              '-export-' +
              formatDate(new Date().getTime() / 1000, 'YYYYMMDD-hhmmss'),
              '.xlsx'
            )
          } else {
            this.$message.success(this.$t('common.export_processing'))
            this.$store.dispatch('app/fetchTaskData')
          }
        }).catch(this.$confirmError)
      } else {
        const downloadFile = (res) => {
          this.$store.dispatch('app/fetchTaskData')
          // createLink(res.url)
          // this.$emit('requested')
        }

        const err = (err) => {
          this.$emit('error')
          this.$message.error(err)
        }

        let keys
        if (!this.type) {
          keys = this.$refs.tree.getCheckedKeys()
        } else {
          keys = [this.treeData[0].id]
          if (this.treeData[0].children) {
            keys.push(...this.treeData[0].children.map((child) => child.id))
          }
        }

        switch (mode) {
          case 1:
            exportParameterTemplateStructureAndData(this.templateId, keys)
              .then(downloadFile)
              .catch(err)
            break
          case 2:
            exportParameterTemplateStructure(this.templateId, keys)
              .then(downloadFile)
              .catch(err)
            break
          case 3:
            exportParameterTemplateData(
              this.templateId,
              keys,
              this.rowUniqueKeyLike
            )
              .then(downloadFile)
              .catch(err)
            break
        }
      }
    }
  }
}
</script>

<style scoped lang="scss">
.terminal-export::v-deep {
  .right-col {
    .el-checkbox {
      margin-right: 5px;
    }

    .el-checkbox__label span {
      display: inline-block;
      width: 200px;
      vertical-align: middle;
    }
  }

  .el-tabs__content {
    padding: 0;
  }

}

.right-col {
  border-left: 1px solid #edf2f9;

}

.download {
  padding: 0 3px;
  border-radius: 3px;

  &:hover {
    background-color: #091e4214;
    color: #172b4d;
  }
}
</style>
